import { useState } from 'react';
import './TestMetaMask.css';
import { ethers } from 'ethers';
import Lock from '../../artifacts/contracts/lock.sol/Lock.json';

const CONTRACT_ADDRESS = '0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9';

function Home() {
    const [address, setAddress] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [contract, setContract] = useState<ethers.Contract | null>(null);

    const connectWallet = async () => {
        try {
            if (!window.ethereum) {
                throw new Error('请安装MetaMask钱包');
            }

            const provider = new ethers.BrowserProvider(window.ethereum);
            const signer = await provider.getSigner();
            const addr = await signer.getAddress();
            setAddress(addr);
            
            // 初始化合约实例
            const contract = new ethers.Contract(CONTRACT_ADDRESS, Lock.abi, signer);
            setContract(contract);
            
            setError(null);
        } catch (err) {
            setError("连接钱包失败，请检查MetaMask设置。");
            console.error(err);
        }
    };

    const setMessage = async () => {
        if (!contract) return;
        
        try {
            const tx = await contract.setMessage('New message');
            await tx.wait();
            alert('消息设置成功！');
        } catch (err) {
            setError("设置消息失败");
            console.error(err);
        }
    };

    return (
        <div className="home-container">
            <h1>区块链测试应用</h1>
            
            <div className="wallet-card">
                {address ? (
                    <div className="wallet-connected">
                        <p>已连接钱包:</p>
                        <p className="wallet-address">{address}</p>
                        <button 
                            className="message-button"
                            onClick={setMessage}
                        >
                            测试消息
                        </button>
                    </div>
                ) : (
                    <button 
                        className="connect-button"
                        onClick={connectWallet}
                    >
                        连接钱包
                    </button>
                )}
                
                {error && <p className="error-message">{error}</p>}
            </div>
        </div>
    );
}

export default Home;